import  random
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart

def send_code(email):
  '''
  发送验证码邮件
  :param email: 邮箱
  :return: 验证码
  '''
  sender_email = 'walrus1983@126.com'  # 发送方邮箱
  sender_password = 'YXUNi39iqZiDWqxb'

  # 你要把邮件发给谁
  receiver_email = email
  code = str(random.randint(10000,99999))

  text_content = '这是一封测试邮件'
  content = f'''<h1 style="color:red;>您的验证码是：{code}</h1>''' + text_content

  # 正文
  # content = "测试邮件内容"
  msg = MIMEMultipart()
  msg.attach(MIMEText(content,'html','utf-8'))

  msg["From"] = formataddr(["walrus1983@126.com",sender_email])
  msg["To"] = Header(receiver_email,"utf-8")
  msg["Subject"] = Header("慕慕手记验证码","utf-8")
  try:
    s = smtplib.SMTP_SSL("smtp.126.com",465)  # 邮箱服务器及端口号
    # s.starttls()
    s.login(sender_email,sender_password)
    s.sendmail(sender_email,receiver_email,msg.as_string())
    flag = True
    s.quit()
    return code
  except Exception as e:
    flag = False
    s.quit()
    return '0'